package com.jcli._java_swing_入门教程pdf.ch17;

import javax.swing.*;
import java.awt.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author li
 * @version 1.0
 * @belongsProject novel_20230923
 * @belongsPackage com.jcli._java_swing_入门教程pdf.ch17
 * @className GridBagLayoutDemo
 * @description TODO  网格包布局管理器
 * @createTime 2024-01-15  23:43
 */
public class GridBagLayoutDemo02 {
    private static final String[] BUTTON_TITLES = {"7", "8", "9", "4", "5", "6", "1", "2", "3", "返回", "拨号"};
    private static final Set<String> SPECIAL_BUTTONS1 = new HashSet<>(Arrays.asList("8", "5", "2", "返回"));
    private static final Set<String> SPECIAL_BUTTONS2 = new HashSet<>(Arrays.asList("9", "6", "3", "拨号"));

    /**
     * 向JFrame中添加JButton按钮
     *
     * @param title         按钮标题
     * @param frame         框架
     * @param gridBagLayout 网格袋布局
     * @param constraints   网格袋约束
     */
    public static void makeButton(String title, JFrame frame, GridBagLayout gridBagLayout, GridBagConstraints constraints) {
        JButton button = new JButton(title);
        gridBagLayout.setConstraints(button, constraints);
        frame.add(button);
    }

    public static void createButtonGroup(JFrame frame, GridBagLayout gridBagLayout, GridBagConstraints constraints) {
        // 设置组件填充显示区域-组件横向、纵向充满其显示区域）
        constraints.fill = GridBagConstraints.BOTH ;
        // 恢复默认值b
        constraints.weightx = 0.0;
        // 结束行
        constraints.gridwidth = GridBagConstraints.REMAINDER;

        JTextField tf = new JTextField("13512345345");
        gridBagLayout.setConstraints(tf, constraints);
        frame.add(tf);

        constraints.weightx = 0.5;
        constraints.weighty = 0.2;
        constraints.gridwidth = 1;

        // 遍历按钮标题数组，添加按钮组件
        for (String buttonTitle : BUTTON_TITLES) {
            makeButton(buttonTitle, frame, gridBagLayout, constraints);
            //嵌套三元运算符
            constraints.gridwidth = (SPECIAL_BUTTONS1.contains(buttonTitle)) ?
                    GridBagConstraints.REMAINDER : ((SPECIAL_BUTTONS2.contains(buttonTitle)) ? 1 : constraints.gridwidth);
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("拨号盘");
        GridBagLayout gridBagLayout = new GridBagLayout();
        GridBagConstraints constraints = new GridBagConstraints();
        frame.setLayout(gridBagLayout);

        createButtonGroup(frame, gridBagLayout, constraints);

        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
